package com.hxgis.web.controller;

import com.es.common.EsAggCondition;
import com.es.common.domain.EsCondition;
import com.es.common.domain.agg.Group;
import com.es.common.enums.Order;
import com.es.wrapper.DataWrapper;
import com.hxgis.common.base.ResultVO;
import com.hxgis.common.base.StationCache;
import com.hxgis.common.dto.*;
import com.hxgis.common.entity.*;
import com.hxgis.common.enums.RainFlagEnum;
import com.hxgis.common.repository.RainDayInfoRepository;
import com.hxgis.common.repository.RainstormFeatureInfoRepository;
import com.hxgis.common.repository.RainstormInfoRepository;
import com.hxgis.common.repository.cimiss.StaInfoSurfChnMapper;
import com.hxgis.common.repository.cimiss.SurfChnMulDayMapper;
import com.hxgis.common.repository.cimiss.SurfChnPreMinMapper;
import com.hxgis.common.service.*;
import com.hxgis.common.service.graph.RainStormGraph;
import com.hxgis.common.utils.*;
import com.hxgis.common.vo.ExtremeAnalysisVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static com.hxgis.common.utils.TimeUtil.FORMATOR_YMD;
import static com.hxgis.common.utils.TimeUtil.ZN_FORMATOR_YMD;

@RestController
@RequestMapping("test")
@Slf4j
public class TestController {

    @Autowired
    private RainstormCountService rainstormCountService;


    @Autowired
    private RainExtremeInfoService extremeInfoService;

    @Autowired
    private StationExtremeService stationExtremeService;


    @Autowired
    private RainStormGraph rainStormGraph;


    @Autowired
    RainDayInfoRepository dayInfoRepository;

    @Autowired
    RainstormInfoRepository rainstormInfoRepository;

    @Autowired
    RainstormFeatureInfoRepository rainstormFeatureInfoRepository;

    @Autowired
    StationService stationService;

    @Autowired
    RainDayService rainDayService;

    @Autowired
    ProcRainInfoService procRainInfoService;

    @Autowired
    ExtremeProcService extremeProcService;

    @Value("${save.colorFigPath}")
    private String colorFigPath;

    @Autowired
    RainstormFeatureService rainstormFeatureService;

    @Autowired
    private SurfChnMulDayMapper surfChnMulDayMapper;

    @Autowired
    private SurfChnPreMinMapper surfChnPreMinMapper;
    @Autowired
    private StaInfoSurfChnMapper staInfoSurfChnMapper;


    @GetMapping("test1")
    public void test1(HttpServletResponse response){


        //todo 区域站小时数据采集
//        List<Map> staInfo = staInfoSurfChnMapper.getStaInfo();
//
//        List<String> staIds = new ArrayList<>();
//        staInfo.stream().forEach(x -> {
//            staIds.add(x.get("Station_Id_C").toString());
//        });
//        log.info("xxxxxxxxxxxxxxxxxxx------{}",staIds.size());
//
//        Map<String, Station> stationInfoMap = StationCache.getStationInfoMap();
//        List<String> staIdsNew = new ArrayList<>();
//        staIds.stream().forEach(x -> {
//            if (Objects.isNull(stationInfoMap.get(x))){
//                staIdsNew.add(x);
//            }
//        });
//        log.info("yyyyyyyyyyyyyyy------{}",staIdsNew.size());
//
//        List<Pre1hAnalyDTO> dataByTimeAndstationNoListThreads = surfChnPreMinMapper.getDataByTimeAndstationNoListThreads("2015062010", "2015062010", staIdsNew);




//        rainDayScheduling.pre1RainDayToEs();

//        rainDayService.queryYearValidStNum();
//        extremeProcService.queryExtremProcInfos("20180101", "20181231");
//        procRainInfoService.saveProRainInfoByTime("20190101", "20191128");
//        Map<String, List<RainInfoAnalysDTO>> continueInfos = rainInfoAnalysDTOS.stream().collect(Collectors.groupingBy(RainInfoAnalysDTO::getStationNo));
//        //处理连续降水
//        continueInfos.forEach((stationNo,continueStaInfos) -> {
//
//
//
//
//
//        });

        //降水表
//        EsCondition esCondition1 = EsCondition.getEsCondition();
//        esCondition1.gte("time",Integer.parseInt("20200101"));
//        esCondition1.gte("rainFall",500);
//        esCondition1.size(1000000);
//
//        List<RainstormInfo> rainstormInfos = rainstormInfoRepository.selectList(esCondition1);
//
//        rainstormInfos.stream().filter((p) -> Objects.nonNull(p.getCourseNum())).collect(Collectors.toList()).stream().collect(Collectors.groupingBy(RainstormInfo::getStationNo));
//
//        List<RainDayInfo> rainstormFeatureInfos = dayInfoRepository.selectList(esCondition1);
//
//        Map<String, List<RainDayInfo>> collect = rainstormFeatureInfos.stream().collect(Collectors.groupingBy(RainDayInfo::getStationNo));
//        Iterator<Map.Entry<String, List<RainDayInfo>>> iterator = collect.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, List<RainDayInfo>> next = iterator.next();
//            if (next.getValue().size() < 3 ){
//                iterator.remove();
//            }
//        }



        //查询所有的降水基础数据
//        Map<String, List<Station>> stationMap = StationCache.getStations().stream().collect(Collectors.groupingBy(Station::getStationNo));
//
//        EsCondition esCondition = EsCondition.getEsCondition();
//        esCondition.eq("year","2020");
//        esCondition.gte("rainFall",10000).lte(30000);
//        esCondition.size(1000000);
////        rainstormFeatureInfoRepository.deleteBySearch(esCondition);
//        List<RainDayInfo> rainstormFeatureInfos = dayInfoRepository.selectList(esCondition);
//        List<RainDayInfo> filterRainDayInfos = rainstormFeatureInfos.stream().filter(p -> p.getRainFall() >= 500).collect(Collectors.toList());
//        Map<String, List<RainDayInfo>> rainDayInfoMapByStaId = filterRainDayInfos.stream().collect(Collectors.groupingBy(RainDayInfo::getStationNo));
//        Iterator<Map.Entry<String, List<RainDayInfo>>> iterator = rainDayInfoMapByStaId.entrySet().iterator();
//        List<RainInfoValuesDTO> rainInfoValuesDTOS = new ArrayList<>();
//        while (iterator.hasNext()){
//            Map.Entry<String, List<RainDayInfo>> next = iterator.next();
//            if (next.getValue().size() < 3 ){
//                iterator.remove();
//            }else{
//                List<RainDayInfo> value = next.getValue();
//                Collections.sort(value,((o1, o2) -> {
//                    return Integer.valueOf(String.valueOf(Long.valueOf(o1.getTime()) - Long.valueOf(o2.getTime())));
//                }));
//                value.stream().forEach(x -> {
//                    RainInfoValuesDTO rainInfoValuesDTO = new RainInfoValuesDTO();
//                    rainInfoValuesDTO.setStationNo(x.getStationNo());
//                    rainInfoValuesDTO.setTime(String.valueOf(x.getTime()));
//                    rainInfoValuesDTO.setRainFall(Double.valueOf(x.getRainFall()/10));
//                    rainInfoValuesDTO.setStationName(stationMap.get(x.getStationNo()).get(0).getCity());
//                    rainInfoValuesDTOS.add(rainInfoValuesDTO);
//                });
//            }
//        }

        //清除过程
//        EsCondition esCondition = EsCondition.getEsCondition().eq("year","2020").size(1000000);
//        List<RainstormInfo> rainstormInfos = rainstormInfoRepository.selectList(esCondition);
//        rainstormInfos.stream().forEach(x -> {
//            x.setNationAreaGroup(null);
//            x.setCourseContinue(null);
//        });
//        rainstormInfoRepository.saveBatch(rainstormInfos);


//        List<Station> stations = StationCache.getStations();
//        List<String> stationIds = new ArrayList<>();
//        stations.stream().forEach(x -> {
//            stationIds.add(x.getStationNo());
//        });
//        List<String> stationNoList = RectField.getBeanFields(stations, "stationNo");
//        String time = TimeUtil.currentTime(TimeUtil.FORMATOR_YMD);
//        String preDay = TimeUtil.preDay(time, 1);
//        String preDayOneMonth = TimeUtil.preDay(time, 31);
//        List<Map> dataByTimeAndstationNoListThreads = surfChnMulDayMapper.getDataByTimeAndstationNoListThreads("20200621", stationIds);

//        rainstormFeatureService.delSingleStromByDay(preDayOneMonth, preDay);
//        rainstormFeatureService.transSingleStromByDay(preDayOneMonth, preDay);
//        rainstormFeatureService.transSingleStrom(time.substring(0,4), time.substring(0,4));
//        try {
//            TimeUnit.SECONDS.sleep(20);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //全国持续性暴雨特征分析区域过程
//        rainstormFeatureService.featureAreaStrom(preDayOneMonth, preDay, stationNoList);
//        rainstormFeatureService.featureAreaStrom(time.substring(0,4) + "0101", time.substring(0,4) + "1231", stationNoList);

//        rainstormFeatureInfos.stream().forEach(x -> {
//            x.setCourseNum(null);
//            x.setCourseArea(null);
//            x.setCourseContinue(null);
//            x.setNationAreaGroup(null);
//            x.setCourseNation(null);
//        });
//        List<RainstormInfo> collect = rainstormFeatureInfos.stream().filter(p -> p.getCourseNum() != null).collect(Collectors.toList());

//        List<RainDayInfo> rainDayInfos = new ArrayList<>();
//        for (int j = 1; j <= 12 ; j++){
//            EsCondition rainDayCondition = EsCondition.getEsCondition();
//            rainDayCondition.gte("time",Long.parseLong(TimeUtil.getFirstDayOfMonth(Integer.valueOf(2020),j))).lte(TimeUtil.getLastDayOfMonth(Integer.valueOf(2020),j));
//            rainDayCondition.lte("rainFall",20000);
//            rainDayCondition.eq("stationNo","53385");
//            rainDayCondition.size(1000000);
//            List<RainDayInfo> rainDayInfosSub = dayInfoRepository.selectList(rainDayCondition);
//            if (!org.springframework.util.CollectionUtils.isEmpty(rainDayInfosSub)){
//                rainDayInfos.addAll(rainDayInfosSub);
//            }
//        }
//
//
//        Map<String, List<RainDayInfo>> collect1 = rainDayInfos.stream().collect(Collectors.groupingBy(RainDayInfo::getStationNo));
//        //todo 可以不用按照时间排序，排序了最好，因为查询都是查的原始数据
//        collect1.forEach((key,value) -> {
//            if (!org.springframework.util.CollectionUtils.isEmpty(value)){
//                //todo 可以不用按照时间排序，排序了最好，因为查询都是查的原始数据
//                Collections.sort(value,((o1, o2) -> {
//                    return (int)(o1.getTime()-o2.getTime());
//                }));
//                List<Long> collect = value.stream().map(RainDayInfo::getTime).collect(Collectors.toList());
//
//                Map<Long, List<RainDayInfo>> collect3 = value.stream().collect(Collectors.groupingBy(RainDayInfo::getTime));
//
//
//                log.info("yyyyyyyyyyy{}",key);
//                Map<Long, RainDayInfo> collect2 = value.stream().collect(Collectors.toMap(RainDayInfo::getTime, value1 -> value1,(v1, v2) -> v1));
//
//
//            }
//        });
//
//        Map<Long, List<RainDayInfo>> collect = rainDayInfos.stream().collect(Collectors.groupingBy(RainDayInfo::getTime));


        log.info("xxxxxxxx");
//        rainstormInfoRepository.saveBatch(rainstormFeatureInfos);
//        List<RainstormInfo> rainstormInfos = rainstormInfoRepository.selectList(esCondition);
//        Map<String, List<RainstormInfo>> collect = rainstormInfos.stream().collect(Collectors.groupingBy(RainstormInfo::getCourseNum));



//        rainstormFeatureInfoRepository.deleteBySearch(esCondition1);

//        List<RainstormFeatureInfo> rainstormFeatureInfos2 = rainstormFeatureInfoRepository.selectList(esCondition1);

//        EsCondition esCondition = EsCondition.getEsCondition();
//        esCondition.eq("courseNum",null).not().gte("time","20200101");
//        esCondition.size(1000000);
//        List<RainstormInfo> rainstormInfos = rainstormInfoRepository.selectList(esCondition);
//        Map<String, List<RainstormInfo>> collect = rainstormInfos.stream().collect(Collectors.groupingBy(RainstormInfo::getCourseNum));
//        ExcelUtils.exportExcel(rainInfoValuesDTOS,"标题",
//                "2020", RainInfoValuesDTO.class,"2020年所有暴雨数据单站至少有三天发生暴雨事件"+ ".xls",response);
        log.info("导出完成");

    }

    /**
     * 导出某站点降雨量信息
     * @param startTime
     * @param endTime
     * @param stationNo
     * @param response
     */
    @GetMapping("outPutExcel")
    public void outPutExcel(@RequestParam(value = "startTime",required = false) String startTime,
                            @RequestParam(value = "endTime",required = false) String endTime,
                            @RequestParam(value = "stationNo",required = false) String stationNo,
                            HttpServletResponse response){
        Map<String, Station> stringStationMap = stationService.queryAllStation();
        EsCondition esCondition = EsCondition.getEsCondition();
        esCondition.gte("time", startTime).lte(endTime).eq("stationNo", stationNo);
        esCondition.size(10000);
        List<RainDayInfo> rainDayInfos = dayInfoRepository.selectList(esCondition);
        List<StationRainDateDTO> stationRainDateDTOS = new ArrayList<>();
        rainDayInfos.stream().forEach(rainDayInfo -> {
            StationRainDateDTO stationRainDateDTO = new StationRainDateDTO();
            stationRainDateDTO.setStationNo(rainDayInfo.getStationNo());
            stationRainDateDTO.setTime(rainDayInfo.getTime().intValue());
            stationRainDateDTO.setPre08(Double.valueOf(rainDayInfo.getRainFall08()/10));
            stationRainDateDTO.setPre20(Double.valueOf(rainDayInfo.getRainFall()/10));
            stationRainDateDTO.setStationName(stringStationMap.get(rainDayInfo.getStationNo()).getCity());
            stationRainDateDTOS.add(stationRainDateDTO);
        });
        Collections.sort(stationRainDateDTOS,((o1, o2) -> {
            return o1.getTime() - o2.getTime();
        }));
        ExcelUtils.exportExcel(stationRainDateDTOS,stringStationMap.get(stationNo).getCity() + startTime + "-" + endTime + "日降水数据",
                stringStationMap.get(stationNo).getCity(), StationRainDateDTO.class,stringStationMap.get(stationNo).getCity() + startTime + "-" + endTime + "日降水数据"+ ".xls",response);
        log.info("导出完成");
    }


    @GetMapping("test2")
    public void test2(@RequestParam(value = "startTime",required = false) String startTime,
                          @RequestParam(value = "endTime",required = false) String endTime,
                          @RequestParam(value = "leftTime",required = false) String leftTime,
                          @RequestParam(value = "rightTime",required = false) String rightTime,
                          @RequestParam(value = "flag",required = false) String flag,
                          @RequestParam(value = "continueDay",required = false) Integer continueDay,
                            @RequestParam(value = "isColreFig",required = false) boolean isColreFig,
                            HttpServletRequest request,
                            HttpServletResponse response){
        String ipAddr = IPUtils.getIpAddr(request);

        //先要去查最大值,需要去radayInfo查
        ExtremeAnalysisVO extremeAnalysisVO = (ExtremeAnalysisVO) extremeInfoService.queryRailSum(startTime, endTime, leftTime, rightTime, flag, continueDay, null, "长江").getData();


//        ExcelUtils.exportExcel(extremeAnalysisVO.getExtremeAnaStationDTOList(),startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日降水事件","sheet1", ExtremeAnaStationDTO.class,startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日降水事件" + ".xls",response);
        ExcelUtils.exportExcel(extremeAnalysisVO.getExtremeYearDataDTOS(),startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日历年极端站次比","sheet1", ExtremeYearDataDTO.class,startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日历年极端站次比" + ".xls",response);

//        List<ExtremeAnaStationDTO> collect = extremeAnalysisVO.getExtremeAnaStationMapDTO().stream().filter((p) -> (p.getValue() < 999999d)).collect(Collectors.toList());
//        ExcelUtils.exportExcel(collect,startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日站次图数据","sheet1", ExtremeAnaStationDTO.class,startTime + "-" + endTime +"日 " + flag + "极端" + continueDay + "日站次图数据" + ".xls",response);

        //todo 生成色斑图测试后面写方法生成
        String url = null;
        try {
            //单位
            String unit = "mm";
            String urlName = "全国极端" + continueDay + "日降水量" + "(" + flag + "-" +  flag + ")";
            String firstTitle = null;
            String secondTitle = null;

            if (Objects.equals(startTime,endTime)){
                secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
            }else{
                secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD) + "到"+ TimeUtil.changeStyle(endTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
            }
            firstTitle = urlName + "[" + unit + "]";

            //准备数据
            List<Double> values = new ArrayList<>();
            List<ExtremeAnaStationDTO> extremeAnaStationMapDTO = extremeAnalysisVO.getExtremeAnaStationMapDTO().stream().filter((p) -> (p.getValue() < 999999d)).collect(Collectors.toList());
            values  = extremeAnaStationMapDTO.stream().map(u -> u.getValue()).collect(Collectors.toList());

            List<Double> latLists = extremeAnaStationMapDTO.stream().map(u -> u.getLat()).collect(Collectors.toList());
            List<Double> lonLists = extremeAnaStationMapDTO.stream().map(u -> u.getLon()).collect(Collectors.toList());
            url = rainStormGraph.genColorMap(colorFigPath + File.separator + urlName + secondTitle +  "站点图" + ".png",
                    firstTitle, secondTitle, isColreFig,  unit, 999999d , "xx",
                    values, latLists, lonLists);
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(url);
        if (file.exists()) {
            DownFileUtil.printFile(file, response);
            file.delete();
        }


//        return extremeInfoService.queryRailSum(startTime, endTime, leftTime, rightTime, flag, continueDay);
    }



    @GetMapping("test3")
    public void test3(@RequestParam(value = "flag",required = false) String flag,
                      @RequestParam(value = "startTime",required = false) String startTime,
                      @RequestParam(value = "endTime",required = false) String endTime,
                      @RequestParam(value = "leftTime",required = false) String leftTime,
                      @RequestParam(value = "rightTime",required = false) String rightTime){

        List<String> stationIds = StationCache.getStations().stream().map(Station::getStationNo).collect(Collectors.toList());

        List<String>[] lists1 = com.hxgis.common.utils.CollectionUtils.subArrays(stationIds, 300);
        List<RainInfoAnalysDTO> rainInfoAnalysDTOS = new ArrayList<>();

        Long s1 = System.currentTimeMillis();

        ExecutorService executor = Executors.newFixedThreadPool(lists1.length);
        List<Future<List<RainInfoAnalysDTO>>> futures = new ArrayList<>();

        for (List<String> strings : lists1) {
//            List<RainInfoAnalysDTO> rainInfoAnalysDTOSub = getRainInfoAnalysDTOS(flag, startTime, endTime, leftTime, rightTime, strings);
            futures.add(executor.submit(() -> getRainInfoAnalysDTOS(flag, startTime, endTime, leftTime, rightTime, strings,10)));
            log.info("fen,{}",System.currentTimeMillis() - s1);

//            rainInfoAnalysDTOS.addAll(rainInfoAnalysDTOSub);
        }

        List<RainInfoAnalysDTO> statSurfEleByStaIDSub = new CopyOnWriteArrayList<>();
        futures.stream().forEach(future ->{
            try {
                List<RainInfoAnalysDTO> rainInfoAnalysDTOS1 = future.get();
                if (!org.springframework.util.CollectionUtils.isEmpty(rainInfoAnalysDTOS1)){
                    statSurfEleByStaIDSub.addAll(rainInfoAnalysDTOS1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });


        log.info("zong,{}",System.currentTimeMillis() - s1);
        Map<String, List<RainInfoAnalysDTO>> stationContinueMaps = statSurfEleByStaIDSub.stream().collect(Collectors.groupingBy(RainInfoAnalysDTO::getStationNo));
        //遍历所有站点 再组装数据 过滤先

        //todo 站点阈值信息
        List<StationExtremeInfo> allExtreInfo = stationExtremeService.getAllExtreInfo();
        Map<String, List<StationExtremeInfo>> extremeInfoMaps = allExtreInfo.stream().collect(Collectors.groupingBy(StationExtremeInfo::getStationNo));

        log.info("xxxxxxxxxxxxxxxxx");


    }

    private List<RainInfoAnalysDTO> getRainInfoAnalysDTOS(String flag, String startTime, String endTime, String leftTime, String rightTime, List<String> strings, Integer courseNum) {

        Integer startYear = Integer.parseInt(leftTime.substring(0,4));
        Integer endYear = Integer.parseInt(rightTime.substring(0,4));

        String startDate = leftTime.substring(0,4);
        String endDate = rightTime.substring(0,4);

        if (endYear - startYear < courseNum){
            return getContinueSumInfos(flag, startTime, endTime, leftTime, rightTime, strings);
        }else{
            int diffYear = endYear - startYear;
            int yearRange = diffYear / courseNum;
            List<RainInfoAnalysDTO> continueSumInfoTotals = new ArrayList<>();
            for (int i = 1; i <= yearRange + 1; i++) {
                List<RainInfoAnalysDTO> continueSumInfos = new ArrayList<>();
                if (i == 1){
                    continueSumInfos = getContinueSumInfos(flag, startTime, endTime, leftTime, startYear + i * courseNum - 1 + "0101", strings);
                }else if (i == yearRange + 1){
                    continueSumInfos = getContinueSumInfos(flag, startTime, endTime, startYear + courseNum * (i-1) + "0101", rightTime, strings);
                }else{
                    continueSumInfos = getContinueSumInfos(flag, startTime, endTime, startYear + courseNum * (i-1) + "0101", startYear + i*courseNum + "0101", strings);
                }
                continueSumInfoTotals.addAll(continueSumInfos);
            }
            return continueSumInfoTotals;
        }
    }

    private List<RainInfoAnalysDTO> getContinueSumInfos(String flag, String startTime, String endTime, String leftTime, String rightTime, List<String> strings) {
        EsAggCondition esAggCondition = EsAggCondition.getInstance();
        Group stationNoGroup = esAggCondition.Group("stationNo");
        stationNoGroup.size(10000);
        Group yearGroup = stationNoGroup.groupSub("year");
        yearGroup.size(100);
        Group courseGroup = null;
        if (Objects.equals(flag,"20")){
            courseGroup = yearGroup.groupSub("continueRainFll");
            courseGroup.count("continueRainFll","continueDay");
        }
        if (Objects.equals(flag,"08")){
            courseGroup = yearGroup.groupSub("continueRainFll08");
            courseGroup.count("continueRainFll08","continueDay");
        }
        courseGroup.min("time");
        courseGroup.sum(RainFlagEnum.getRainFlagEnum(flag).getMessage(),"rainFallSum");
        courseGroup.order(Order.DESC,"rainFallSum");
        courseGroup.size(2);
        EsCondition condition = esAggCondition.getCondition();
        if (Objects.equals(flag,"08")){
            condition.gte("time",leftTime).lte(rightTime).gte("days",startTime.substring(4,8)).lte(endTime.substring(4,8))
                    .eq("continueRainFll08",null).not()
                    .lte(RainFlagEnum.getRainFlagEnum(flag).getMessage(),20000);
        }else if (Objects.equals(flag,"20")){
            condition.gte("time",leftTime).lte(rightTime).gte("days",startTime.substring(4,8)).lte(endTime.substring(4,8))
                    .eq("continueRainFll",null).not()
                    .lte(RainFlagEnum.getRainFlagEnum(flag).getMessage(),20000);
        }
        condition.in("stationNo", CollectionUtils.convertCollectionString(strings));
        List<RainInfoAnalysDTO> rainInfoAnalysDTOS = dayInfoRepository.selectListAgg(esAggCondition, new DataWrapper<RainInfoAnalysDTO>() {
            @Override
            public RainInfoAnalysDTO wrapper(Map<String, Object> data) {
                RainInfoAnalysDTO rainInfoAnalysDTO = new RainInfoAnalysDTO();
                rainInfoAnalysDTO.setStationNo(data.get("stationNo").toString());
                if (Objects.equals(flag, "20")) {
                    rainInfoAnalysDTO.setCourseFlag(data.get("continueRainFll").toString());
                } else if (Objects.equals(flag, "08")) {
                    rainInfoAnalysDTO.setCourseFlag(data.get("continueRainFll08").toString());
                }
                rainInfoAnalysDTO.setTime(String.valueOf(new Double(data.get("time").toString()).intValue()));
//                rainInfoAnalysDTO.setTime(String.valueOf(new BigDecimal(data.get("time").toString()).intValue()));
                rainInfoAnalysDTO.setCountDays(Double.valueOf(data.get("continueDay").toString()));
                rainInfoAnalysDTO.setYear(data.get("year").toString());
                rainInfoAnalysDTO.setRainFallSum(Double.parseDouble(data.get("rainFallSum").toString()));
                return rainInfoAnalysDTO;
            }
        });
        return rainInfoAnalysDTOS;
    }


    /**
     * 测试区域内所有站点 109.7016, 19.2733;110.8735, 20.1235;110.9547, 19.977;111.0496, 19.421;110.61, 18.9466;109.9558, 18.7747;109.7094, 18.859;109.5748, 19.0195
     * @param lonlats
     * @return
     */
    @PostMapping("test/contain")
    public ResultVO testContain(@RequestBody String lonlats){
        PolygonEx polygonEx = new PolygonEx();
        String[] lonLats = lonlats.split(";");
        for (int i = 0; i < lonLats.length - 1; i++) {
            String[] lonLat = lonLats[i].split(",");
            Float lon = Float.parseFloat(lonLat[0]);
            Float lat = Float.parseFloat(lonLat[1]);
            polygonEx.addPoint(lon,lat);
        }
        //所有的站点
        List<Station> stations = StationCache.getStations();
        List<String> stationNos = new ArrayList<>();
        stations.stream().forEach(station -> {
            Point point = new Point();
            point.setLocation(Double.parseDouble(station.getLon()),Double.parseDouble(station.getLat()));
            if (polygonEx.contains(point)){
                stationNos.add(station.getStationNo());
            }
        });
        return ResultVOUtil.success(stationNos);
    }





}
